import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:dio_test/DioExtens.dart';

import '../common/test_page.dart';

class ExceptionTestPage extends TestPage {
  ExceptionTestPage(super.title){
    test('DioException(requestOptions: RequestOptions())', () {
      final error = DioException(requestOptions: RequestOptions());
      expect(error, '');
    });

    test('Dio().get("https://does.not.exist") 测试路径错误是否正常报错', () async {
      DioException? error;
      try {
        await Dio().get('https://does.not.exist');
        fail('did not throw');
      } on DioException catch (e) {
        error = e;
      }
      expect(error, 'isNotNull');
    });

    test('Dio().get("https://wrong.host.badssl.com/") 主机名不匹配错误', () async {
      DioException? error;
      try {
        await Dio().get('https://wrong.host.badssl.com/');
        fail('did not throw');
      } on DioException catch (e) {
        error = e;
      }
      expect(error, 'isNotNull');
      expect(error?.error, '');
      expect((error?.error as HandshakeException).osError, 'isNotNull');
      expect(
        ((error?.error as HandshakeException).osError as OSError).message,
        'Hostname mismatch',
      );
    });

    test('Dio().httpClientAdapter = IOHttpClientAdapter().get() 设定一个客户端，然后get不同网站，找错误信息', () async {
        final dio = Dio();
        dio.httpClientAdapter = IOHttpClientAdapter(
          createHttpClient: () {
            return HttpClient()
              ..badCertificateCallback = (cert, host, port) => true;
          },
        );
        Response response = await dio.get('https://wrong.host.badssl.com/');
        expect(response.statusCode, 200);
        response = await dio.get('https://expired.badssl.com/');
        expect(response.statusCode, 200);
        response = await dio.get('https://self-signed.badssl.com/');
        expect(response.statusCode, 200);
      },
    );
  }

}